#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void ChildWrite(int fd)
{
    char buffer[1024]={0};
    int time=10;
    while(time)
    {
        snprintf(buffer, sizeof(buffer),"child: pid= %d ppid= %d timr= %d fd= %d",getpid(),getppid(),time,fd);
        write(fd ,buffer,sizeof(buffer));
        sleep(1);
        time--;
    }
}

void FatherRead(int fd)
{
    char buffer[1024]={0};
    int readret = read(fd,buffer,sizeof(buffer)-1);
    if (readret>0)
    {
        std::cout<<"father: "<<buffer<<std::endl;
    }
    else
    {
        std::cout<<readret<<std::endl;
    }
}

int main()
{
    int fds[2]={0};
    int piperet = pipe(fds);

    std::cout<<"fds[0]: "<<fds[0]<<std::endl;
    std::cout<<"fds[1]: "<<fds[1]<<std::endl;

    pid_t childid = fork();
    if(childid==0)
    {
        //子进程
        close(fds[0]);
        ChildWrite(fds[1]);
        sleep(20);
        close(fds[1]);
        std::cout<<"子进程结束"<<std::endl;

    }
    else if (childid>0)
    {
        //父进程
        close(fds[1]);
        int num=20;
        while(num--)
        {
            FatherRead(fds[0]);
        }

        close(fds[0]);
        std::cout<<"父进程结束"<<std::endl;
        int status=0;
        pid_t rid=0;
        rid = waitpid(childid, &status, 0);
        if (rid>0)
        {
            if(WIFEXITED(status))
            {
                printf("wait success rid: %d | exit code: %d | exit signal %d \n",rid ,WEXITSTATUS(status),status&0x7f);
            }
        }

    }
    else
    {
        perror("fork: ");
        exit(1);
    }


    return 0;
} 
